'''
1、加密的数据  uid
2、算法  python模块
3、密钥 flask_app SECRET_KEY
'''
import functools
from itsdangerous import TimedSerializer as Serializer
from flask import current_app, request
from flask_shop.models import User
import base64
import time
from flask_shop.utils.message import to_dict_msg


def generate_auth_token(uid, expiration):
    # 创建加密对象
    s = Serializer(current_app.config['SECRET_KEY'])
    # 生成token
    token = s.dumps({'uid': uid, 'expiration': expiration, 'time': int(time.time())})
    return base64.b64encode(token.encode('utf-8')).decode('utf-8')


def verify_auth_token(token_str):
    # 创建解密对象
    s = Serializer(current_app.config['SECRET_KEY'])
    # 解密
    token = base64.b64decode(token_str).decode('utf-8')
    try:
        data = s.loads(token)
        if int(time.time()) - data['time'] > data['expiration']:
            # 业务逻辑暂时省略
            return to_dict_msg(10017)
    except Exception as e:
        print(e)
        return to_dict_msg(10016)
    user = User.query.filter_by(id=data['uid']).first()
    return user


def login_required(view_func):
    @functools.wraps(view_func)
    def wrapped_view(*args, **kwargs):
        try:
            token = request.headers.get('token')
            if not token:
                return to_dict_msg(10016)
        except Exception as e:
            return to_dict_msg(10016)
        verify_auth_token(token)
        return view_func(*args, **kwargs)
    return wrapped_view


# if __name__ == '__main__':
#     res = generate_auth_token('123456', 3600)
#     print(res)
